<?php
/**
 * Description of TransDetail 交易详情共用处理
 *
 * @author Mike Gao
 */
class TransDetailAction extends CommonAction{
    
    /**
     *update stock,
     * write log
     * update Finance
     * @param <type> $field default is name
     */
    public  function update($field='name') {
        //B('FilterString');
        $name=$this->getActionName();
        $p_name = str_replace('_detail', '', $name);    //Parent Action Name (OverView Action)
        $model = D ( $name );
        $id = intval($_POST['id']);
        $old = $model->where('id = '.$id)->find();
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        // 更新数据
        $list=$model->save ();
        if (false !== $list) {
            $new = $model->where('id = '.$id)->find();

            //如果修改了数量，则同时更新库存
            if(($diff = ( $new['number'] -  $old['number']) ) != 0 && $p_name != 'Broken'){
                $product_id = getModelName($id, $name, 'product_id');
                if ($p_name == 'Switch') {
                    A('Trans')->updateStock($product_id, $new['from_warehouse_id'], 'out', $diff);
                    A('Trans')->updateStock($product_id, $new['to_warehouse_id'], 'in', $diff);
                } else {
                    $warehouse_id = getModelName($new[strtolower($p_name) . '_id'], $p_name, 'warehouse_id');
                    if($p_name == 'Sale' )
                        $order_status = getModelName( $new['sale_id'],'Sale','order_status' );
                    //如果是订单，且订单状态为已发货，则减去库存
                    //TODO 已发货的订单，是否不可以修改产品数量？
                    if ( ($p_name == 'Sale' && $order_status == 3) || $p_name == 'Back_supplier'){
                         A('Trans')->updateStock($product_id, $warehouse_id, "out", $diff);
                    }
                    if ($p_name == 'Sale_back' || $p_name == 'Enter'){
                         A('Trans')->updateStock($product_id, $warehouse_id, "in", $diff);
                    }
                   
                }
            }

            if ($p_name == "Buy") {
                M('Buy')->where('id = '.$new['buy_id'])->setField('finish',is_all_finish($new['buy_id']));
            }

            //如果修改了价格，则同时更新total
            $price = ($p_name == "Enter" || $p_name == "Buy" )? $_POST['enter_price']:$_POST['price'];
            updateTotalPrice($p_name,$id,$_POST['number'],$price);

            //update sum_number
            if($p_name != 'Switch')
                updateSumNumber($p_name,$id,$_POST['number']);

            //日志记录
            $mod_field = getModelName ($id, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
            //成功提示
            $jumpUrl = $_REQUEST['jumpUrl'];
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this->success ('编辑成功!');
        } else {
            //错误提示
            $this->error ('编辑失败!');
        }
    }

    public function foreverdelete($field='name'){
        //删除指定记录
        $name=$this->getActionName();
        $model = D ($name);
        $p_name = str_replace('_detail', '', $name);    //Parent Action Name (OverView Action)
       
        if (! empty ( $model )) {
            $pk = $model->getPk ();
            $id = $_REQUEST [$pk];
            if (isset ( $id )) {
                 $small_type = strtolower($p_name);
                 $p_id = getModelName($id,$small_type.'_detail',$small_type.'_id');
   
                $condition = array ($pk => array ('in', explode ( ',', $id ) ) );
                $old = $model->where($condition)->findAll();
                $mod_field = getModelName($id, $name, $field);
                if (false !== $model->where($condition)->delete()) {
                    $new = array();
                    $msg = '删除 ' . $name . ': ' . $mod_field . ' (编号：' . $id . ')';
                    if ('Action' != $name)
                        A('Action')->writeLog($msg, '删除', $name,$id, $old,$new);
                    //同时更新缓存
                    $this->update_cache( $name );
                     //如果修改了数量，则同时更新库存 TODO
                    /*
                    if(($diff = ( $new['number'] -  $old['number']) ) != 0 && $p_name != 'Broken'){
                        $product_id = getModelName($id, $name, 'product_id');
                        if ($p_name == 'Switch') {
                            A('Trans')->updateStock($product_id, $new['from_warehouse_id'], 'in', $diff);
                            A('Trans')->updateStock($product_id, $new['to_warehouse_id'], 'out', $diff);
                        } else {
                            $warehouse_id = getModelName($new[strtolower($p_name) . '_id'], $p_name, 'warehouse_id');
                            if ($p_name == 'Sale' || $p_name == 'Back_supplier')
                                $type = 'out';
                            if ($p_name == 'Sale_back' || $p_name == 'Enter')
                                $type = 'in';
                            A('Trans')->updateStock($product_id, $warehouse_id, $type, $diff);
                        }
                    }*/

                    //如果修改了价格，则同时更新total
                    updateTotalPrice($p_name,$id,0,0);
                    $total = $model->where($small_type.'_id = '.$p_id)->sum('total');
                    M($p_name)->where('id = '.$p_id)->setField('total',$total);
                   

                    //TODO 现仅适用于单个删除情况
                    //update sum_number
                    if($p_name != 'Switch'){
                        $total = $model->where($small_type.'_id = '.$p_id)->sum('number');
                        M($p_name)->where('id = '.$p_id)->setField('sum_number',$total);
                    }

                    $this->success('删除成功！');
                } else {
                    $this->error ('删除失败！');
                }
            } else {
                $this->error ( '非法操作' );
            }
        }
        $this->forward ();
    }

    public function  _before_insert() {
        $_POST['product_id'] = empty ($_POST['ptm_id'])?(
                $_POST['product_id'] = empty ($_POST['ppy_id'])? 
                ($_POST['product_id'] = empty ($_POST['hz_id'])? 0:$_POST['hz_id'])
                    : $_POST['ppy_id'] ) : $_POST['ptm_id'];

        if( empty($_POST['product_id']) )
            $this->error("必须选择产品");

        if($_POST['number'] < 1)
            $this->error("产品数量必须大于1");

        $name=$this->getActionName();
        $parent_name = strtolower( str_replace('_detail', '', $name) );
        if(empty($_POST[$parent_name.'_id']) )
            $this->error("必须选择单号");
    }


    /**
     * 插入同时，记录相应的日志
     * @param <string> $filed  记录的字段名称，默认为name
     */
    function insert($field='name') {
        //B('FilterString');
        $name=$this->getActionName();
        $model = D ($name);
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
        //update stock
        $parent_name = str_replace('_detail', '', $name);    //Parent Action Name (OverView Action)
        
        //更新库存
        if( $parent_name != 'Broken' and $parent_name != "Buy"){ //采购及破损不更新库存 TODO 破损也要处理库存
                $product_id = $_POST['product_id'];
                $diff = $_POST['number'];

                if ($p_name == 'Switch') {
                    A('Trans')->updateStock($product_id, $_POST['from_warehouse_id'], 'out', $diff);
                    A('Trans')->updateStock($product_id, $_POST['to_warehouse_id'], 'in', $diff);
                } else {
                    $warehouse_id = getModelName( $_POST[ strtolower($parent_name).'_id'],$parent_name,'warehouse_id');
                    if ($parent_name == 'Sale' || $parent_name == 'Back_supplier')
                        $type = 'out';
                    if ($parent_name == 'Sale_back' || $parent_name == 'Enter')
                        $type = 'in';
                    A('Trans')->updateStock($product_id, $warehouse_id, $type, $diff);
                }
            }

            //如果修改了价格，则同时更新财务记录
            $price = ($parent_name == "Enter" || $parent_name == "Buy" )? $_POST['enter_price']:$_POST['price'];
            updateTotalPrice($parent_name,$list,$_POST['number'],$price);

            //update sum_number
            if($p_name != 'Switch')
                updateSumNumber($parent_name,$list,$_POST['number']);

            /******************日志记录*********************/
             $mod_field = getModelName ($list, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '新增 '.$name.': '.$mod_field.' (编号：'.$list.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'新增',$name,$list);
            $jumpUrl = $_REQUEST['jumpUrl'];
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this->success ('新增成功!');
        } else {
            //失败提示
            $this->error ('新增失败!');
        }
    }

}
?>
